from datetime import datetime
import time
from abc import ABC, abstractmethod

from sqlalchemy import select

from forward.dependencies.database import db
from forward.exceptions.base import AppException
from forward.api.pc.schemas.sms import SmsSendInSchema, SystemLogSmsSchema
from forward.http_base import HttpResp
from forward.model.tables.system import SystemLogSmsModel
from forward.plugins.notice.notice_driver import NoticeDriver
from forward.utils.tools import ToolsUtil


class SmsSendService:

    async def send(self, send_params: SmsSendInSchema):
        """
        发送验证码
        :param send_params:
        :return:
        """

        sms_log_record = await db.fetch_one(
            select(SystemLogSmsModel.id, SystemLogSmsModel.create_time)
            .select_from(SystemLogSmsModel)
            .where(
                SystemLogSmsModel.mobile == send_params.mobile,
                SystemLogSmsModel.scene == send_params.scene,
                SystemLogSmsModel.status.in_({0, 1}),
            )
            .order_by(SystemLogSmsModel.id.desc())
        )
        sms_log = SystemLogSmsSchema.model_validate(
            sms_log_record, from_attributes=True
        )
        if sms_log and sms_log.created_time <= datetime.now():
            raise AppException(HttpResp.FAILED, msg="操作频繁,请稍后再试!!")

        sms_params = {
            "scene": send_params.scene,
            "mobile": send_params.mobile,
            "params": {"code": ToolsUtil.random_int(4)},
        }

        await NoticeDriver().handle(sms_params)

    @classmethod
    async def instance(cls):
        """实例化"""
        return cls()
